package link.chengguo.orangemall.service.ams.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import link.chengguo.orangemall.ams.entity.AmsAgent;
import link.chengguo.orangemall.ams.entity.AmsAgentBrokerageLevel;
import link.chengguo.orangemall.ams.mapper.AmsAgentMapper;
import link.chengguo.orangemall.ams.model.params.AmsAgentParam;
import link.chengguo.orangemall.ams.model.result.AmsAgentResult;
import link.chengguo.orangemall.ams.service.IAmsAgentBrokerageLevelService;
import link.chengguo.orangemall.ams.service.IAmsAgentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.enums.AllEnum;
import link.chengguo.orangemall.exception.BusinessMallException;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.sys.service.ISysUserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author yzb
 * @date 2019-12-21
 */
@Service
public class AmsAgentServiceImpl extends ServiceImpl
        <AmsAgentMapper, AmsAgent> implements IAmsAgentService {

    @Resource
    private AmsAgentMapper amsAgentMapper;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private IAmsAgentBrokerageLevelService agentBrokerageLevelService;


    @Override
    public boolean resetAgentPwd(Long agentId) throws Exception {
        SysUser parm=new SysUser();
        AmsAgent agent=amsAgentMapper.selectById(agentId);
        parm.setCityCode(agent.getCityCode());
        parm.setParentId(0L);
        parm.setShopId(0L);
        SysUser admin=sysUserService.getOne(new QueryWrapper<>(parm));
        String md5Password = passwordEncoder.encode("123456");
        admin.setPassword(md5Password);
        sysUserService.updateById(admin);
        return true;
    }

    @Transactional
    @Override
    public boolean createAgent(AmsAgent amsAgent) throws Exception{
        //判定该城市是否已经有代理
        if (StringUtils.isEmpty(amsAgent.getCityCode())){
            throw new RuntimeException("代理城市不能为空");
        }
        if (this.getAgentByCityCode(amsAgent.getCityCode())!=null){
            throw new RuntimeException("选择的城市已有代理");
        }
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", amsAgent.getAccount()));
        if(user != null){
            throw new RuntimeException("账号已存在");
        }
        user = new SysUser();
        //创建代理账号
        user.setPlatform(AllEnum.PlatformType.Agent.code());//代理用户
        user.setUsername(amsAgent.getAccount());
        user.setNickName(amsAgent.getName());
        user.setPassword(amsAgent.getPassword());
        user.setCityCode(amsAgent.getCityCode());
        user.setSupplyId(1L);
        sysUserService.saves(user);
        //抽佣等级
        AmsAgentBrokerageLevel level=agentBrokerageLevelService.getById(amsAgent.getBrokerageLevel());
        amsAgent.setBrokeragePercent(level.getPercent());
        amsAgentMapper.insert(amsAgent);
        return true;
    }

    @Transactional
    @Override
    public boolean updateAgent(AmsAgent amsAgent) throws Exception {
        //更新代理密码
        if (!StringUtils.isEmpty(amsAgent.getPassword())){
            SysUser user=new SysUser();
            user.setPlatform(AllEnum.PlatformType.Agent.code());//代理用户
            user.setUsername(amsAgent.getAccount());
            user.setSupplyId(1L);
            String md5Password = passwordEncoder.encode(amsAgent.getPassword());
            user.setPassword(md5Password);
            //根据账号更新店铺管理者密码
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("username",amsAgent.getAccount());
            if ( sysUserService.update(user,queryWrapper)==false){
                throw new RuntimeException("密码更新失败");
            }
        }
        //抽佣等级
        AmsAgentBrokerageLevel level=agentBrokerageLevelService.getById(amsAgent.getBrokerageLevel());
        amsAgent.setBrokeragePercent(level.getPercent());
        //更新代理信息
        amsAgent.setPassword(null);
        amsAgentMapper.updateById(amsAgent);
        return true;
    }

    @Override
    public AmsAgent getAgentByCityCode(String cityCode) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("city_code",cityCode);
        return amsAgentMapper.selectOne(queryWrapper);
    }

    @Override
    public Page<AmsAgentResult> customPageList(Integer pageNum, Integer pageSize, AmsAgentParam paramCondition) {
        Page page1= new Page<>();
        page1.setSize(pageSize);
        page1.setCurrent(pageNum);
        return amsAgentMapper.customPageList(page1,paramCondition);
    }

    @Transactional
    @Override
    public boolean updateAgentPwd(Long userId, String oldPwd, String newPwd) throws Exception {
        SysUser user=sysUserService.getById(userId);
        if (!passwordEncoder.matches(oldPwd, user.getPassword())) {
            throw new BusinessMallException("旧密码错误");
        }
        String newpd = passwordEncoder.encode(newPwd);
        user.setPassword(newpd);
        //根据账号更新店铺管理者密码
        if ( sysUserService.updateById(user)==false){
            throw new RuntimeException("密码更新失败");
        }
        //同步下代理数据表的密码，暂时没啥作用
        AmsAgent agent=this.getAgentByCityCode(user.getCityCode());
        agent.setPassword(newpd);
        amsAgentMapper.updateById(agent);
        return true;
    }
}
